
//c_string version 4
////optimize swap
////using assert

//using my own atoi

#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* #define NDEBUG */
#include <assert.h>
void reverse(char v[])
{
  int i = 0;
  int j = strlen(v) - 1;
  for(;i<j;i++,j--) {
    v[i] = v[i]+v[j];
    v[j] = v[i]-v[j];
    v[i] = v[i]-v[j];
  }
}

void itoa(int n, char v[])
{
  int sign = n;
  int i = 0;//index of v[]
 
  if(n<0)
    n=-n;//the behavior of negative / and % are left implementation dependent.
  //deal with 0
  do
    v[i++] = n%10+'0';
  while(n/=10);

  if(sign<0)//followed by sign
    v[i++] = '-';

  v[i] = '\0'; //followed by '\0'

  reverse(v);//reverse a c_str
}

//support sign and decimal
int atoi(char v[])
{
  int sign = 1;
  int i = 0;//index of v[]
  int sum =0;
  if(v[0] == '-'){
    sign = -1;
    i++;
  }
  else if(v[0] == '+') {
    sign = 1;
    i++;
  }
  else {
    sign = 1;
    assert(isdigit(v[0]));
  }

  for(;v[i] != '\0';i++){
    assert(isdigit(v[i]));
    sum = sum*10 + v[i]-'0';
  }

  sum = sign*sum;
  return sum;
} 


int main(int argc, char *argv[])
{

  int num = 1984;
  char v[12];
  if(argc == 2)
    num = atoi(argv[1]);

  itoa(num,v);
  assert(num == atoi(v));
  printf("the c_str is\t:%s\n",v);
  //-----------------------------------
  num = 1984;
  itoa(num,v);
  assert(num == atoi(v));
  //-----------------------------------
  num = -1984;
  itoa(num,v);
  assert(num == atoi(v));
 //-----------------------------------
  num = 0;
  itoa(num,v);
  assert(num == atoi(v));
 //-----------------------------------
  num = -1;
  itoa(num,v);
  assert(num == atoi(v));
  return 0;
}
